package com.example.financeapi.job;

import com.alibaba.fastjson.JSONObject;
import com.example.financeapi.config.ExceptionExample;
import com.example.financeapi.config.annotation.SystemJobLog;
import com.example.financeapi.config.constant.APIConstant;
import com.example.financeapi.config.wechat.miniapp.WxMaProperties;
import com.example.financeapi.config.wechat.mp.WxMpProperties;
import com.example.financeapi.entity.FTaskErrorLog;
import com.example.financeapi.mapper.FTaskErrorLogMapper;
import com.example.financeapi.utils.HttpUtil;
import com.example.financeapi.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@Slf4j
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling   // 2.开启定时任务
public class TokenJob {

    @Autowired
    private RedisUtils strRedis;
    @Autowired
    private WxMpProperties wxMpProperties;
    @Autowired
    private WxMaProperties wxMaProperties;
    @Autowired
    private FTaskErrorLogMapper fTaskErrorLogMapper;

    @Async
    @SystemJobLog(description = "每2小时获取一下微信的Token")
    //@Scheduled(cron = "0 0/3 * * * ?")
    @Scheduled(cron = "0 0 0/2 * * ?")
    public void getTokenTasks() {
        try{
            //1.获取微信公众号的access_token
            wxMpProperties.getConfigs().forEach(item->{
                String getMyAppId = item.getAppId();
                String getMyAppSecret = item.getSecret();
                String getToken =strRedis.get("mp_access_token-"+getMyAppId);
                if(StringUtils.isEmpty(getToken)) {
                    String getTokenApi = String.format(APIConstant.MX_ACCESS_TOKEN_URL, getMyAppId, getMyAppSecret);
                    String tokenJsonStr = HttpUtil.doGetPost(getTokenApi, "GET", null);
                    JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
                    log.info("【定时任务 getTokenTasks】 定时任务获取接口结果： tokenJsonStr={},getMyAppId={}",tokenJsonStr,getMyAppId);
                    getToken = tokenJson.get("access_token").toString();
                    strRedis.set("mp_access_token-" + getMyAppId, getToken, APIConstant.TOKEN_TIMES);
                }
                //log.info("【定时任务 getTokenTasks】 定时任务获取微信公众号access_token getAppId={},access_token={}",getMyAppId,getToken);
            });

            //2.获取微信小程序的access_token
            wxMaProperties.getConfigs().forEach(item->{
                String getMyAppId = item.getAppid();
                String getMyAppSecret = item.getSecret();
                String getToken =strRedis.get("miniapp_access_token-"+getMyAppId);
                if(StringUtils.isEmpty(getToken)) {
                    String getTokenApi = String.format(APIConstant.MX_ACCESS_TOKEN_URL, getMyAppId, getMyAppSecret);
                    String tokenJsonStr = HttpUtil.doGetPost(getTokenApi, "GET", null);
                    JSONObject tokenJson = JSONObject.parseObject(tokenJsonStr);
                    log.info("【定时任务 getTokenTasks】 定时任务获取小程序access_token结果： tokenJsonStr={}",tokenJsonStr);
                    getToken = tokenJson.get("access_token").toString();
                    strRedis.set("miniapp_access_token-" + getMyAppId, getToken, APIConstant.TOKEN_TIMES);
                }
                //log.info("【定时任务 getTokenTasks】 定时任务获取微信小程序access_token getAppId={},access_token={}",getMyAppId,getToken);
            });
        } catch (Exception ex) {
            FTaskErrorLog fTaskErrorLog =new FTaskErrorLog();
            fTaskErrorLog.setTaskName("getTokenTasks");
            fTaskErrorLog.setCause(ExceptionExample.getExceptionType(ex)+"");
            fTaskErrorLog.setMessage(ExceptionExample.getExceptionMessage(ex));
            fTaskErrorLog.setTrackingStack(ExceptionExample.getExceptionSrintStackTrace(ex));
            fTaskErrorLogMapper.insert(fTaskErrorLog);
            log.error("【定时任务】定时刷新access_token出现异常：{}，原因：{},msg={}", ex.getMessage(), ex.getCause(),ex);
        }
    }
}
